import {useNavigate} from "react-router-dom";
import {
    Button, ButtonGroup,
    Popover, PopoverArrow, PopoverBody, PopoverCloseButton,
    PopoverContent, PopoverFooter,
    PopoverHeader,
    PopoverTrigger,
    Stack,
    useColorModeValue,
    useToast
} from "@chakra-ui/react";
import {useAuth} from "../../hooks/index.js";
import React, {useEffect, useState} from "react";
import {handleResult, handleResultNoRoute} from "../../api/result.js";
import {DoctorShowSearchBar} from "../../components/DoctorShowSearchBar.jsx";
import {BellIcon, CalendarIcon, CheckIcon, TimeIcon} from "@chakra-ui/icons";
import {
    getAllOrderPage,
    getAllOrderPageDid,
    findByName,
    getOrderCount,
    updateOrder,
    updateOrderStatus
} from "../../api/order.js";

export function DoctorOrderManagePage() {
    const navigator = useNavigate()
    const toast = useToast()
    const authInfo = JSON.parse(localStorage.getItem('auth-info'))

    // 数据获取
    const [orders, setOrders] = useState([])
    const [total, setTotal] = useState([])
    useEffect(() => {
        // if (!localStorage.getItem('auth-info')) {
        //     toast({
        //         title: '请登录!',
        //         status: 'error',
        //         position: 'top',
        //         isClosable: true,
        //     })
        //     navigator('/login')
        //     return
        // }
        // 请求数据
        getAllOrderPageDid({page: 0, size: 6, did: authInfo.doctor.id})
            .then((data) => {
                setOrders(data.data)
                console.log(data)
            })
        getOrderCount().then(r => {
            setTotal(r.data)
        })
    }, []);


    // SearchBar states
    const [value, setValue] = useState('')
    let timer = new Date()
    const [startDate, setStartDate] = useState(timer.toLocaleDateString())
    const [endDate, setEndDate] = useState(timer.toLocaleDateString())

    let searchItem = {
        placeholder: '医生或学生名称',
        value,
        onChange: (e) => {
            setValue(e.target.value)
        },
        onClick: (e) => {
            if (value === '') {
                getAllOrderPageDid({page: 0, size: 6}).then(r => {
                    handleResultNoRoute(r, toast, '', '查询成功')
                    setOrders(r.data)
                })
                return
            }
            findByName(value).then(r => {
                handleResultNoRoute(r, toast, '', '查询成功')
                setOrders(r.data)
            })
        }
    }
    let dateSearchItem = {
        onChange: (date, dateString) => {
            console.log(date, dateString)
            setStartDate(dateString[0])
            setEndDate(dateString[1])
        },
        onClick: (e) => {
            console.log(startDate, endDate)
        }
    }
    // 当前页码
    const [curIdx, setCurIdx] = useState(0);
    let pageSearchItem = {
        total: (Math.floor(total / 6) + 1), curIdx,
        onChange: (e) => {
            setCurIdx(e.target.value)
        },
        onLeftClick: () => {
            console.log(curIdx)
            if (curIdx > 1) {
                setCurIdx((curIdx - 1))
                return
            }
            toast({
                title: `已到达第一页!`,
                status: 'warning',
                position: 'top',
                isClosable: true,
            })
        },
        onRightClick: () => {
            if (curIdx < (Math.floor(total / 6) + 1)) {
                setCurIdx((curIdx + 1))
                return
            }
            toast({
                title: `已到达最后一页!`,
                status: 'warning',
                position: 'top',
                isClosable: true,
            })
        },
        onClick: () => {
            getAllOrderPageDid({page: curIdx, size: 6, did: authInfo.doctor.id})
                .then(r => {
                    handleResultNoRoute(r, toast, '', '查询成功')
                    setOrders(r.data)
                })
        }
    }

    // 叫号
    const handleOrderClick = (oid, sid) => {
        console.log(oid)
        console.log(sid)
        console.log(authInfo.doctor.id)
        // 修改order状态为 1-已就诊(叫号)
        updateOrderStatus({
            id: oid,
            studentId: sid,
            doctorId: authInfo.doctor.id,
            status: 1
        }).then(r => handleResult(r, toast, '', '叫号成功'))
    }

    const handleMedicineListAdd = (id) => {
        // oid <-> hid <-> mhid
        // 跳转开药界面
        navigator(`/doctor/manage/medicine/${id}`)
    }

    return (
        <Stack
            align={'start'}
            justify={'start'}
            mb={6}
            className={useColorModeValue('', 'dark')}
            spacing={4}
        >
            <DoctorShowSearchBar
                pageSearchItem={pageSearchItem}
                searchItem={searchItem}
                dateSearchItem={dateSearchItem}/>
            <div className={"table-container"}>
                <table className="table table-hover mt-3">
                    <thead>
                    <tr>
                        <th>名称</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    {
                        orders.map((item) => (
                                <tr key={item.id}>
                                    <td>{item.student.name}</td>
                                    <td>{item.createTime}</td>
                                    <td>
                                        <Stack direction='row' spacing={4}>
                                            {item.status === '0' ?
                                                < Button
                                                    onClick={() =>
                                                        handleOrderClick(item.id, item.student.id)}
                                                    leftIcon={<BellIcon/>} size='sm'
                                                    colorScheme='green' variant='solid'>
                                                    叫号
                                                </Button> :
                                                <Button
                                                    disabled
                                                    leftIcon={<TimeIcon/>}
                                                    size='sm'
                                                    colorScheme='gray' variant='solid'>
                                                    已叫
                                                </Button>
                                            }
                                            <Button
                                                onClick={() => handleMedicineListAdd(item.id)}
                                                leftIcon={<CalendarIcon/>} size='sm'
                                                colorScheme='green' variant='solid'>
                                                开药
                                            </Button>
                                        </Stack>
                                    </td>
                                </tr>
                            )
                        )
                    }
                    </tbody>
                </table>
            </div>
        </Stack>
    )
}